package news

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/news"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	var req struct {
		Page       int  `binding:"required,gte=1,max=10000000"`
		Limit      int  `binding:"required,gte=1,max=10000000"`
		CategoryId uint `binding:"max=255"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	// 查询
	var count int64
	type organization struct {
		ID   uint
		Name string
	}
	var list []struct {
		ID             uint
		Title          string
		Thumb          string
		Top            string
		CategoryId     uint
		OrganizationId uint `json:"-"`
		ReleaseTime    string
		Organization   organization
	}

	var tx = bean.MysqlDb.Model(&news.News{})

	tx.Where("`check_status`=?", "已审")

	if req.CategoryId != 0 {
		tx.Where("`category_id`=?", req.CategoryId)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Preload("Organization").Limit(req.Limit).Offset(offset).Order("`top` ASC").Order("`release_time` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func Detail(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var tx = bean.MysqlDb.Model(&news.News{})

	tx.Where("`check_status`=?", "已审")

	tx.Where("id=?", req.ID)

	type organization struct {
		ID   uint
		Name string
	}

	var one struct {
		news.News
		Organization organization
	}

	if err := tx.Preload("Organization").First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("文章不存在id:%d", req.ID))
		return
	}

	c.PureJSON(200, one)
}
